/**
@description open_api文件

@copyright    Copyright 2021 高灯科技
@version      1.0.0
@link         https://www.goldentec.com
@author       venki.chen <venki.chen@goldentec.com>
@datetime     2021/12/10 10:42
*/

package main

import (
	"context"
	"encoding/json"
	"gitee.com/venki/go_study_accumulate/go_review/20211208/proto/prime"
	"gitee.com/venki/go_study_accumulate/go_review/20211208/proto/sum"
	"github.com/micro/go-micro"
	api "github.com/micro/go-micro/api/proto"
	"strconv"
)

var (
	sumClient   sum.SumService
	primeClient prime.PrimeService
)

type Open struct {
}

//
//	Fetch
//	@Description
//	@receiver open Open
//	@param ctx context.Context
//	@param req *api.Request
//	@param rsp *api.Response
//	@return error
//  @maxim from focus to execute
//  @author venki.chen
//  @createdtime 2021-12-10 10:54:57
//  @updatedtime 2021-12-10 10:54:57
//
func (open Open) Fetch(ctx context.Context, req *api.Request, rsp *api.Response) error {
	// 接受参数
	sumInputStr := req.Get["sum"].Values[0]
	primeInputStr := req.Get["prime"].Values[0]

	// 参数处理
	sumInput, _ := strconv.ParseInt(sumInputStr, 10, 10)
	primeInput, _ := strconv.ParseInt(primeInputStr, 10, 10)

	// 实例化请求体
	sumReq := &sum.SumRequest{
		Input: sumInput,
	}
	primeReq := &prime.PrimeRequest{
		Input: primeInput,
	}

	// 调用客户端
	sumRsp, _ := sumClient.GetSum(ctx, sumReq)
	primeRsp, _ := primeClient.GetPrime(ctx, primeReq)

	ret, _ := json.Marshal(map[string]interface{}{
		"sum":   sumRsp,
		"prime": primeRsp,
	})

	rsp.Body = string(ret)

	return nil
}

func main() {
	// 1. 创建服务
	service := micro.NewService(
		micro.Name("go.micro.learning.api.open"),
	)

	sumClient = sum.NewSumService("go.micro.learning.srv.sum", service.Client())
	primeClient = prime.NewPrimeService("go.micro.learning.srv.prime", service.Client())

	// TODO 暴露接口

	if err := service.Run(); err != nil {
		panic(err)
	}
}
